package org.example.projecttwo.controller.content;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.example.projecttwo.common.Result;
import org.example.projecttwo.common.utils.ArticleNoGenerator;
import org.example.projecttwo.entity.article.Article;
import org.example.projecttwo.entity.article.ArticlePartition;
import org.example.projecttwo.entity.dto.content.request.*;
import org.example.projecttwo.entity.dto.content.response.ArticleDetailVO;
import org.example.projecttwo.service.Iarticle.IArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/articles")
@Tag(name = "文章管理", description = "文章信息管理")
public class ArticleController {

    @Autowired
    private IArticleService articleService;

    @GetMapping("/list")
    @Operation(summary = "分页查询文章列表", description = "分页查询文章列表，支持状态、分区、精品和时间范围筛选 -- 文章管理")
    public Result<IPage<Article>> listArticles(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String partitionCode,
            @RequestParam(required = false) Integer isFeatured,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        Page<Article> page = new Page<>(current, size);
        IPage<Article> result = articleService.pageByCondition(
                page, status, partitionCode, isFeatured, keyword, startTime, endTime);
        return Result.success(result);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取文章详情", description = "根据文章ID获取文章详情，包含完整信息 -- 文章管理")
    public Result<ArticleDetailVO> getArticle(@PathVariable Long id) {
        ArticleDetailVO article = articleService.getArticleDetail(id);
        return Result.success(article);
    }

    @PostMapping
    @Operation(summary = "新增文章", description = "新增文章，默认状态为草稿 -- 文章管理")
    public Result<Article> createArticle(@Valid @RequestBody Article article) {
        article.setStatus(0);
        String articleNo = ArticleNoGenerator.generateArticleNo();
        article.setArticleNo(articleNo);

        articleService.save(article);
        return Result.success(article);
    }

    @PutMapping("/{id}")
    @Operation(summary = "修改文章", description = "修改文章信息 -- 文章管理")
    public Result<Article> updateArticle(@PathVariable Long id, @Valid @RequestBody Article article) {
        Article existing = articleService.getById(id);
        if (existing == null) {
            return Result.error("文章不存在");
        }
        // 已发布/审核通过的文章不可直接编辑
        if (existing.getStatus() == 2) {
            return Result.error("已发布文章不可编辑，请先下架");
        }
        article.setId(id);
        articleService.updateById(article);
        return Result.success(articleService.getById(id));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除文章", description = "根据文章ID删除文章，支持10天内恢复 -- 文章管理")
    public Result<String> deleteArticle(
            @PathVariable Long id,
            @Valid @RequestBody Map<String, Object> params) {
        Integer deleteReason = (Integer) params.get("reason");
        String deleteRemark = (String) params.get("remark");

        if (deleteReason == null) {
            return Result.error("请选择删除原因");
        }

        ContentDeleteDTO deleteDTO = new ContentDeleteDTO();
        deleteDTO.setDeleteReason(deleteReason);
        deleteDTO.setDeleteRemark(deleteRemark);
        articleService.deleteArticle(id, deleteDTO);
        return Result.success("删除成功，10天内可恢复");
    }

    @PutMapping("/{id}/submit-audit")
    @Operation(summary = "提交审核", description = "将文章状态改为待审核 -- 文章管理")
    public Result<String> submitAudit(@PathVariable Long id) {
        articleService.updateStatus(id, 1); // 1=待审核
        return Result.success("提交审核成功");
    }

    @PutMapping("/{id}/publish")
    @Operation(summary = "发布文章", description = "将文章状态改为审核通过 -- 文章管理")
    public Result<String> publishArticle(@PathVariable Long id) {
        articleService.updateStatus(id, 2); // 2=审核通过
        return Result.success("发布成功");
    }

    @PutMapping("/{id}/unpublish")
    @Operation(summary = "下架文章", description = "将文章状态改为已下架，并记录下架原因 -- 文章管理")
    public Result<String> unpublishArticle(
            @PathVariable Long id,
            @Valid @RequestBody Map<String, Object> params) {

        Integer offShelfReason = (Integer) params.get("offShelfReason");

        if (offShelfReason == null) {
            return Result.error("请选择下架原因");
        }

        ContentOffShelfDTO offShelfDTO = new ContentOffShelfDTO();
        offShelfDTO.setOffShelfReason(offShelfReason);
        articleService.unpublishArticle(id, offShelfDTO);

        return Result.success("下架成功");
    }

    @PostMapping("/batch-publish")
    @Operation(summary = "批量审核通过", description = "批量将文章状态改为审核通过 -- 文章管理")
    public Result<String> batchPublish(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一篇文章");
        }
        articleService.batchUpdateStatus(ids, 2);
        return Result.success("批量审核通过成功,共" + ids.size() + "篇");
    }

    @PostMapping("/batch-unpublish")
    @Operation(summary = "批量下架文章", description = "批量将文章状态改为已下架，并记录下架原因 -- 文章管理")
    public Result<String> batchUnpublish(
            @Valid @RequestBody BatchOperationDTO batchOperationDTO) {
        List<Long> ids = batchOperationDTO.getIds();
        Integer offShelfReason = batchOperationDTO.getReason();

        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一篇文章");
        }
        if (offShelfReason == null) {
            return Result.error("请选择下架原因");
        }

        articleService.batchUnpublish(ids, offShelfReason);
        return Result.success("批量下架成功,共" + ids.size() + "篇");
    }

    @PostMapping("/batch-delete")
    @Operation(summary = "批量删除文章", description = "批量删除文章，支持10天内恢复 -- 文章管理")
    public Result<String> batchDelete(
            @Valid @RequestBody BatchOperationDTO batchOperationDTO) {
        List<Long> ids = batchOperationDTO.getIds();
        Integer deleteReason = batchOperationDTO.getReason();
        String deleteRemark = batchOperationDTO.getRemark();

        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一篇文章");
        }
        if (deleteReason == null) {
            return Result.error("请选择删除原因");
        }

        articleService.batchDelete(ids, deleteReason, deleteRemark);
        return Result.success("批量删除成功,共" + ids.size() + "篇");
    }

    @PutMapping("/{id}/featured")
    @Operation(summary = "设为精品", description = "将文章设为精品文章 -- 文章管理")
    public Result<String> setFeatured(@PathVariable Long id) {
        articleService.updateFeaturedStatus(id, 1); // 1=精品
        return Result.success("设为精品成功");
    }

    @PutMapping("/{id}/unfeatured")
    @Operation(summary = "取消精品", description = "取消文章的精品状态 -- 文章管理")
    public Result<String> cancelFeatured(@PathVariable Long id) {
        articleService.updateFeaturedStatus(id, 0); // 0=非精品
        return Result.success("取消精品成功");
    }

    @GetMapping("/published-count")
    @Operation(summary = "获取已发布文章数量", description = "统计已发布文章的数量 -- 文章管理")
    public Result<Integer> getPublishedCount() {
        int count = articleService.countPublishedArticles();
        return Result.success(count);
    }

    @PutMapping("/{id}/audit")
    @Operation(summary = "审核文章", description = "审核文章并更新状态 -- 文章管理")
    public Result<String> auditArticle(
            @PathVariable Long id,
            @Valid @RequestBody ArticleAuditDTO auditDTO) {  // 接收JSON格式参数
        if (auditDTO.getAuditResult() == 3 && (auditDTO.getRejectReason() == null || auditDTO.getRejectReason().isEmpty())) {
            return Result.error("审核未通过时必须填写拒绝原因");
        }
        articleService.auditArticle(id, auditDTO.getAuditResult(), auditDTO.getRejectReason());
        return Result.success(auditDTO.getAuditResult() == 2 ? "审核通过" : "审核未通过");
    }

    @PostMapping("/batch-audit")
    @Operation(summary = "批量审核文章", description = "批量审核文章并更新状态 -- 文章管理")
    public Result<String> batchAudit(
            @Valid @RequestBody BatchArticleAuditDTO batchDTO) {  // 批量审核DTO
        List<Long> ids = batchDTO.getIds();
        Integer auditResult = batchDTO.getAuditResult();
        String rejectReason = batchDTO.getRejectReason();

        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一篇文章");
        }
        if (auditResult == 3 && (rejectReason == null || rejectReason.isEmpty())) {
            return Result.error("审核未通过时必须填写拒绝原因");
        }

        articleService.batchAudit(ids, auditResult, rejectReason);
        return Result.success(auditResult == 2 ?
                "批量审核通过成功，共" + ids.size() + "篇" :
                "批量审核未通过成功，共" + ids.size() + "篇");
    }


    @GetMapping("/{id}/statistics")
    @Operation(summary = "获取文章统计数据", description = "获取文章的浏览、点赞、收藏等统计信息 -- 文章管理")
    public Result<Map<String, Integer>> getArticleStatistics(@PathVariable Long id) {
        Map<String, Integer> stats = articleService.getArticleStatistics(id);
        return Result.success(stats);
    }

    @GetMapping("/partitions")
    @Operation(summary = "获取所有文章分区", description = "获取所有可用的文章分区列表 -- 文章管理")
    public Result<List<ArticlePartition>> getPartitions() {
        List<ArticlePartition> partitions = articleService.getAllPartitions();
        return Result.success(partitions);
    }

    @PostMapping("/partitions")
    @Operation(summary = "新增文章分区", description = "添加新的文章分区 -- 文章管理")
    public Result<ArticlePartition> addPartition(@Valid @RequestBody ArticlePartition partition) {
        articleService.savePartition(partition);
        return Result.success(partition);
    }

    @PutMapping("/partitions/{code}")
    @Operation(summary = "更新文章分区", description = "修改文章分区信息 -- 文章管理")
    public Result<ArticlePartition> updatePartition(
            @PathVariable String code,
            @Valid @RequestBody ArticlePartition partition) {
        articleService.updatePartition(code, partition);
        return Result.success(partition);
    }

    @DeleteMapping("/partitions/{code}")
    @Operation(summary = "删除文章分区", description = "删除指定的文章分区 -- 文章管理")
    public Result<String> deletePartition(@PathVariable String code) {
        articleService.deletePartition(code);
        return Result.success("分区删除成功");
    }

    @PostMapping("/partitions/save")
    @Operation(summary = "批量保存分区", description = "批量保存文章分区设置 -- 文章管理")
    public Result<String> savePartitions(@Valid @RequestBody List<ArticlePartition> partitions) {
        articleService.saveOrUpdatePartitions(partitions);
        return Result.success("分区设置保存成功");
    }

    @PutMapping("/{id}/view")
    @Operation(summary = "增加文章浏览量", description = "记录文章的浏览次数 -- 文章管理")
    public Result<String> increaseViewCount(@PathVariable Long id) {
        articleService.increaseViewCount(id);
        return Result.success("浏览量记录成功");
    }

    @GetMapping("/drafts/{userId}")
    @Operation(summary = "获取指定用户文章草稿", description = "获取指定用户的所有文章草稿 -- 文章管理")
    public Result<List<Article>> getUserDrafts(@PathVariable Long userId) {
        if (userId == null || userId <= 0) {
            return Result.error("用户ID无效");
        }
        List<Article> drafts = articleService.getUserDraftsByUserId(userId);
        return Result.success(drafts);
    }

    @DeleteMapping("/drafts/{id}")
    @Operation(summary = "删除文章草稿", description = "删除指定的文章草稿 -- 文章管理")
    public Result<String> deleteDraft(@PathVariable Long id) {
        articleService.deleteDraft(id);
        return Result.success("草稿删除成功");
    }

    @PostMapping("/drafts/submit")
    @Operation(summary = "提交草稿审核", description = "提交文章草稿进行审核 -- 文章管理")
    public Result<String> submitDraft(@RequestParam Long id,
                                      @RequestParam(required = false) String coverUrl,
                                      @RequestParam Integer publishStrategy,
                                      @RequestParam(required = false) String publishTime) {
        articleService.submitDraftForAudit(id, coverUrl, publishStrategy, publishTime);
        return Result.success("草稿提交审核成功");
    }

    @GetMapping("/deleted/list")
    @Operation(summary = "获取已删除文章列表", description = "分页查询已删除的文章列表 -- 文章管理")
    public Result<IPage<Article>> listDeletedArticles(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        Page<Article> page = new Page<>(current, size);
        IPage<Article> result = articleService.pageDeletedArticles(page, keyword);
        return Result.success(result);
    }

    @PostMapping("/deleted/restore")
    @Operation(summary = "恢复已删除文章", description = "恢复指定的已删除文章 -- 文章管理")
    public Result<String> restoreDeletedArticles(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一篇文章");
        }
        articleService.restoreDeletedArticles(ids);
        return Result.success("恢复成功，共" + ids.size() + "篇");
    }

    @PostMapping("/deleted/permanent")
    @Operation(summary = "永久删除文章", description = "永久删除指定的已删除文章，不可恢复 -- 文章管理")
    public Result<String> permanentlyDeleteArticles(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一篇文章");
        }
        articleService.permanentlyDeleteArticles(ids);
        return Result.success("永久删除成功，共" + ids.size() + "篇");
    }

    @PostMapping("/deleted/batch-restore")
    @Operation(summary = "批量恢复已删除文章", description = "批量恢复指定的已删除文章 -- 文章管理")
    public Result<String> batchRestoreDeletedArticles(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一篇文章");
        }
        articleService.restoreDeletedArticles(ids);
        return Result.success("批量恢复成功，共" + ids.size() + "篇");
    }

    @PostMapping("/deleted/batch-permanent")
    @Operation(summary = "批量永久删除文章", description = "批量永久删除指定的已删除文章，不可恢复 -- 文章管理")
    public Result<String> batchPermanentlyDeleteArticles(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择至少一篇文章");
        }
        articleService.permanentlyDeleteArticles(ids);
        return Result.success("批量永久删除成功，共" + ids.size() + "篇");
    }
}